package znet

import (
	"fmt"
	"net"
	ziface "zinx/Ziface"
)

// IServer的接口实现
type Server struct {
	Name      string //服务器名称
	IPVersion string
	IP        string
	port      int
}

// 启动服务器
func (s *Server) Start() {
	//获取一个TCP的addr
	fmt.Printf("[Start] Server Listenner at IP:%s,Port:%d is starting\n", s.IP, s.port)
	addr, err := net.ResolveTCPAddr(s.IPVersion, fmt.Sprintf("%s:%d", s.IP, s.port))
	if err != nil {
		fmt.Println("resolve tcp addt error: ", err)
		return
	}
	go func() {
		//listen
		listener, err := net.ListenTCP(s.IPVersion, addr)
		if err != nil {
			fmt.Println("listen tcp error: ", err)
			return
		}

		fmt.Println("start Zinx server sucess:", s.Name, "sucess Listenning...")
		//accept
		for {
			conn, err := listener.Accept()
			if err != nil {
				fmt.Println("Accept err", err)
				continue
			}

			//已经建立好套接字
			//先写一个回响业务
			go func() {
				for {
					buf := make([]byte, 512)
					cnt, err := conn.Read(buf)
					if err != nil {
						fmt.Println("recv buf err", err)
						return
					}
					fmt.Printf("recv client buf:%s,cnt:%d\n", buf, cnt)
					//回响
					if _, err := conn.Write(buf[:cnt]); err != nil {
						fmt.Println("write back buf err", err)
						continue
					}
				}
			}()
		}
	}()

}

// 停止服务器
func (s *Server) Stop() {
	//回收资源
}

// 运行服务器
func (s *Server) Serve() {
	s.Start()
	//设置为阻塞状态,防止主线程结束，导致s.Start协程介绍
	select {}
}

/*
	初始化Server模块的方法
*/

func NewServer(name string) ziface.IServer {
	s := &Server{
		Name:      name,
		IPVersion: "tcp4",
		IP:        "0.0.0.0",
		port:      8999,
	}

	return s
}
